package com.wxlsoft.ui.conflist;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.filechooser.FileFilter;

import com.wxlsoft.ui.ShowErrorMessage;

public class XmlFileChooseListener implements ActionListener {

	private final JLabel label;
	private final JFileChooser chooser;
	
	public XmlFileChooseListener(JLabel label, JFileChooser chooser) {
		this.label = label;
		this.chooser = new JFileChooser();
		this.chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		this.chooser.setFileFilter(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return file.isDirectory() || isXml(file);
			}
			@Override
			public String getDescription() {
				return "*.xml (文本文件)";
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		// 显示文件打开的对话框
		int result = chooser.showOpenDialog(label.getParent());
		if (result == JFileChooser.APPROVE_OPTION) { 
			File file = chooser.getSelectedFile();
			if (!(file.isDirectory() || isXml(file))) {
				ShowErrorMessage.show("文件格式错误");
				return;
			}
			label.setText(file.getAbsolutePath());
		}
	}

	public boolean isXml(File file) {
		return file.getName().toLowerCase().endsWith(".xml");
	}
	
}
